package com.blog.cloud.core.handler;

import com.blog.cloud.core.exception.BlogException;
import com.blog.cloud.core.utils.R;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * controller层的专属异常处理器
 */
@RestControllerAdvice(basePackages = "com.blog.cloud.*.controller")
public class GlobalExceptionHandler {

    /**
     * 数据校验异常处理
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<Object> exceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String, Object> map = new HashMap<>();
        fieldErrors.forEach(fieldError -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.failed(map);
    }

    /**
     * BlogException异常处理
     */
    @ExceptionHandler(value = BlogException.class)
    public R<Object> exceptionHandler(BlogException e) {
        return R.failed(e.getMessage());
    }

    /**
     * 其余异常处理
     */
    @ExceptionHandler(value = Exception.class)
    public R<Object> exceptionHandler(Exception e) {
        return R.failed(e.getMessage());
    }
}
